#ifndef MAINCONTROLLER_H
#define MAINCONTROLLER_H

#include <QList>
#include <QSharedData>
#include <QQmlApplicationEngine>

#include <QXmppClient.h>
#include <QXmppRosterManager.h>
#include <QXmppVCardManager.h>
#include <QXmppVCardIq.h>

#include "global/xnamespace.h"

X_BEGIN_NAMESPACE

//----------------------------------------
// 私有数据
//----------------------------------------
class ApplicationEnginePrivate : public QSharedData
{
public:
    ApplicationEnginePrivate() { }
    ApplicationEnginePrivate(const ApplicationEnginePrivate &other) : QSharedData(other){}

public:
    bool m_sslError = false;
    QXmppClient m_xmppClient;

public:
    const static QString ROOT_VIEW;
};

// 应用程序引擎
class ApplicationEngine : public QQmlApplicationEngine
{
    Q_OBJECT

signals:
    void signInSucceed();
    void signInFailed(QString, QString);
    void signOutSucceed();

public:
    ApplicationEngine(QObject *parent = Q_NULLPTR);
    ApplicationEngine(const ApplicationEngine& src);
    ApplicationEngine(const QUrl &url, QObject *parent = Q_NULLPTR);
    ApplicationEngine(const QString &filePath, QObject *parent = Q_NULLPTR);

    ApplicationEngine &operator =(const ApplicationEngine& rhs);
    bool operator==(const ApplicationEngine &other) const;
    inline bool operator!=(const ApplicationEngine &other) const;

public:
    void run();

    QXmppClient &xmppClient();
    QXmppRosterManager &rosterManager();
    QXmppVCardManager &vcardManager();
    QXmppVersionManager &versionManager();

public slots:
    // RootView Slots
    void onSignIn(const QString& username, const QString& password, int availableStatus = 0);
    void onSignOut();

    // XMPP Client Slots
    void onXmppServerConnected();
    void onXmppServerDisconnected();
    void onXmppClientStateChanged(QXmppClient::State state);

    void onXmppMessageReceived(const QXmppMessage &message);
    void onXmppPresenceReceived(const QXmppPresence &presence);
    void onXmppIqReceived(const QXmppIq& iq);

    void onXmppClientConnecionError(QXmppClient::Error error);
    void onXmppSslErrors(const QList<QSslError>& errors);

    // Roster Slots
    void onRosterReceived();
    void onPresenceChanged(const QString &bareJid, const QString &resource);
    void onSubscriptionReceived(const QString &bareJid);
    void onItemAdded(const QString &bareJid);
    void onItemChanged(const QString &bareJid);
    void onItemRemoved(const QString &bareJid);

    // VCard Slots
    void onVCardReceived(const QXmppVCardIq &vcardIq);
    void onClientVCardReceived();

private:
    void connectXmppSignals();
    void connectRootViewSignals();

private:
    QSharedDataPointer<ApplicationEnginePrivate> d;
};

X_END_NAMESPACE

#endif // MAINCONTROLLER_H
